package com.itheima.store.web.servlet;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itheima.store.domain.User;
import com.itheima.store.service.UserService;
import com.itheima.store.utils.BaseServlet;
import com.itheima.store.utils.BeanFactory;

import dingtalk.org.access.service.impl.OrgServiceImpl;
import dingtalk.org.access.service.impl.SystemConfServiceImpl;
import dingtalk.org.access.util.HttpRequestHelper;


import dingtalk.org.access.util.ErrorCode;

import dingtalk.org.access.util.LogFormatter;
import dingtalk.org.access.util.ServiceResult;
import dingtalk.org.access.vo.DeptSimpileVO;
import dingtalk.org.access.vo.EmpSimpileVO;

/**
 * Servlet implementation class DingServlet
 */
public class DingServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;
	  private static final Logger mainLogger = LoggerFactory.getLogger(DingServlet.class);
	    private static final Logger bizLogger = LoggerFactory.getLogger("EMP_LOGGER");
	   
	  
	    private HttpRequestHelper httpRequestHelper = new HttpRequestHelper();
	
	    
	    private SystemConfServiceImpl systemConfService = new SystemConfServiceImpl();
	  
	    private OrgServiceImpl orgService = new OrgServiceImpl();
	
	/**
	 * 获取钉钉的用户ID
	 */
	public  String getUserId(HttpServletRequest req,HttpServletResponse resp) {
       
        try {
        	/*String url2 = systemConfService.getOapiDomain()+"/gettoken?corpid="+systemConfService.getCorpId()+"&corpsecret="+systemConfService.getCorpSecret();
            String tokenResult = httpRequestHelper.doHttpGet(url2);
            JSONObject tokenObject2 = JSON.parseObject(tokenResult);*/
        	String code = req.getParameter("code");
        	System.out.println("钉钉的code："+code);
            ServiceResult<String> tokenSr = orgService.getOrgAccessToken();
           /* if (!tokenSr.isSuccess()) {
                return ServiceResult.failure(ErrorCode.SYS_ERROR);
            }*/
            String accessToken = tokenSr.getResult();
          //  String url = systemConfService.getOapiDomain() + "/user/simplelist?access_token=" + accessToken + "&department_id=" + 2989072L;
           // String codes= "25d095a4eda833399e1257efa3bcd4af";
            String url = systemConfService.getOapiDomain() + "/user/getuserinfo?access_token=" + accessToken + "&code=" + code;
            
          System.out.println("测试钉钉----------------------------------------------");
          System.out.println(code);
          System.out.println(accessToken);
          System.out.println(url);
            
            
            String empResult = httpRequestHelper.doHttpGet(url);
            JSONObject tokenObject = JSON.parseObject(empResult);
            String userid =  tokenObject.getString("userid");
            Long errCode = tokenObject.getLong("errcode");
            if (null == errCode || errCode.intValue() != 0) {
                bizLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                        "获取用户简单信息失败",
                        LogFormatter.KeyValue.getNew("deptId", 2989072L)
                ));
               // return ServiceResult.failure(ErrorCode.SYS_ERROR);
                return null;
            }
            String url2 = systemConfService.getOapiDomain() + "/user/get?access_token=" + accessToken + "&userid=" + userid;
            String empResult2 = httpRequestHelper.doHttpGet(url2);
            JSONObject tokenObject2 = JSON.parseObject(empResult2);
            String name =  tokenObject2.getString("name");
         // 调用业务层:
           

            
         			UserService userService = (UserService) BeanFactory.getBean("userService");
         			
         			User existUser = userService.loginDing(name);
         			resp.getWriter().println("1");
         			req.getSession().setAttribute("existUser", existUser);
    				resp.sendRedirect(req.getContextPath()+"/index.jsp");
            	   return null;
            /*JSONArray empArr = tokenObject.getJSONArray("userlist");
            List<EmpSimpileVO> empList = JSONArray.parseArray(empArr.toJSONString(), EmpSimpileVO.class);
            return ServiceResult.success(empList);*/
        } catch (Throwable e) {
            mainLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                    LogFormatter.KeyValue.getNew("deptId", 2989072L)
            ));
           // return ServiceResult.failure(ErrorCode.SYS_ERROR);
            return null;
       }
    }

	 //获取所有部门
    public List<DeptSimpileVO> getOrgDeptList(Long deptId) {
        bizLogger.info(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                LogFormatter.KeyValue.getNew("deptId", deptId)
        ));
        try{
            ServiceResult<String> tokenSr = orgService.getOrgAccessToken();
           /* if(!tokenSr.isSuccess()){
                return ServiceResult.failure(ErrorCode.SYS_ERROR);
            }*/
            String accessToken = tokenSr.getResult();
            String url = systemConfService.getOapiDomain()+"/department/list?access_token="+accessToken;
            String deptResult = httpRequestHelper.doHttpGet(url);
            JSONObject tokenObject = JSON.parseObject(deptResult);
            Long errCode = tokenObject.getLong("errcode");
            if(null==errCode || errCode.intValue()!=0){
                bizLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                        "获取ORG 部门列表失败",
                        LogFormatter.KeyValue.getNew("deptId", deptId)
                ));
               // return ServiceResult.failure(ErrorCode.SYS_ERROR);
                return null;
            }
            JSONArray deptArr = tokenObject.getJSONArray("department");
            List<DeptSimpileVO> deptList = JSONArray.parseArray(deptArr.toJSONString(), DeptSimpileVO.class);
            //return ServiceResult.success(deptList);
            return deptList;
        }catch (Throwable e){
            mainLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                    LogFormatter.KeyValue.getNew("deptId", deptId)
            ),e);
           // return ServiceResult.failure(ErrorCode.SYS_ERROR);
            return null;
        }
    }
 //通过部门ID获取部门下所有人员的信息
    public List<EmpSimpileVO> getOrgEmpList(Long deptId) {
        bizLogger.info(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                LogFormatter.KeyValue.getNew("deptId", deptId)
        ));
        try {
            ServiceResult<String> tokenSr = orgService.getOrgAccessToken();
           /* if (!tokenSr.isSuccess()) {
                return ServiceResult.failure(ErrorCode.SYS_ERROR);
            }*/
            String accessToken = tokenSr.getResult();
            String url = systemConfService.getOapiDomain() + "/user/simplelist?access_token=" + accessToken + "&department_id=" + deptId;
            String empResult = httpRequestHelper.doHttpGet(url);
            JSONObject tokenObject = JSON.parseObject(empResult);
            Long errCode = tokenObject.getLong("errcode");
            if (null == errCode || errCode.intValue() != 0) {
                bizLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                        "获取部门下的用户简单信息列表失败",
                        LogFormatter.KeyValue.getNew("deptId", deptId)
                ));
               // return ServiceResult.failure(ErrorCode.SYS_ERROR);
                return null;
            }
            JSONArray empArr = tokenObject.getJSONArray("userlist");
            List<EmpSimpileVO> empList = JSONArray.parseArray(empArr.toJSONString(), EmpSimpileVO.class);
           // return ServiceResult.success(empList);
            return empList;
        } catch (Throwable e) {
            mainLogger.error(LogFormatter.getKVLogData(LogFormatter.LogEvent.END,
                    LogFormatter.KeyValue.getNew("deptId", deptId)
            ));
           // return ServiceResult.failure(ErrorCode.SYS_ERROR);
            return null;
        }
    }
	
}
